import { useState, useEffect } from 'react'
import {
  Button,
  Form,
  Input,
  InputNumber,
  message,
  Select,
  Switch,
  Upload,
} from 'antd'
import axios from 'axios'
import Layout from '../../components/layout'
import { API } from '../../config'
import { Auth } from '../../store/models/auth'
import { isAuth } from '../../utils/auth'
import { PlusOutlined } from '@ant-design/icons'
import { useDispatch, useSelector } from 'react-redux'
import { GET_CATEGORY_LIST } from '../../store/actions/category'
import { Category } from '../../store/models/category'
import { AppState } from '../../store/reducers'
import { RcFile } from 'antd/lib/upload'

const { Option } = Select

export default function CreateProduct() {
  const dispatch = useDispatch()

  useEffect(() => {
    dispatch({ type: GET_CATEGORY_LIST }) // 获取分类列表
  }, [dispatch])

  const categoryList = useSelector<AppState>(
    ({ category }) => category.categoryList
  ) as Category[]

  const [loading, setLoading] = useState<boolean>(false)
  const [imageUrl, setImageUrl] = useState<string>('')
  const [imageFile, setImageFile] = useState<RcFile>()

  const {
    user: { _id },
    token,
  } = isAuth() as Auth

  const indent = 3

  const [form] = Form.useForm()

  function beforeImageUpload(file: RcFile) {
    // console.log(file)
    const allowedFormats = ['image/jpeg', 'image/png'] // 允许的文件格式
    const maxSize = 1024 * 1024 * 2 // 2MB

    if (!allowedFormats.includes(file.type)) {
      message.error('You can only upload JPG/PNG file!')
    }
    if (file.size > maxSize) {
      message.error('Image must smaller than 2MB!')
    }

    setImageUrl(URL.createObjectURL(file))
    setImageFile(file)

    return false
  }

  interface Product {
    photo: RcFile
    name: string
    description: string
    price: number
    category: string
    stock: number
    shipping: boolean
  }

  function onFinish(product: Product) {
    if (!imageFile) {
      message.error('请上传图片')
      return
    }

    setLoading(true)

    const requestBody = new FormData()
    product.photo = imageFile
    requestBody.set('photo', imageFile)
    requestBody.set('name', product.name)
    requestBody.set('description', product.description)
    requestBody.set('price', product.price + '')
    requestBody.set('category', product.category)
    requestBody.set('quantity', product.stock + '')
    requestBody.set('shipping', product.shipping + '')

    axios
      .post(`${API}/product/create/${_id}`, requestBody, {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      })
      .then(res => {
        message.success(`商品 ${res.data.name} 添加成功`)
        // 重置表单
        form.resetFields()
        setImageUrl('')
        setImageFile(undefined)
      })
      .catch(err => {
        message.error({
          key: 'create-category-error',
          content: err.response.data.error,
        })
      })
      .finally(() => {
        setLoading(false)
      })
  }

  return (
    <Layout title='Create Product'>
      <Form
        form={form}
        labelCol={{
          span: indent,
        }}
        onFinish={onFinish}
        initialValues={{
          name: '',
          photo: '',
        }}
      >
        <Form.Item label='Product Picture'>
          <Upload
            action='/'
            maxCount={1}
            listType='picture-card'
            showUploadList={false}
            beforeUpload={beforeImageUpload}
          >
            {imageUrl ? (
              <img src={imageUrl} alt='avatar' style={{ width: '100%' }} />
            ) : (
              <div>
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>Upload</div>
              </div>
            )}
          </Upload>
        </Form.Item>
        <Form.Item
          label='Product Name'
          name='name'
          rules={[{ required: true }]}
        >
          <Input type='text' />
        </Form.Item>
        <Form.Item
          label='Product Description'
          name='description'
          rules={[{ required: true }]}
        >
          <Input type='text' />
        </Form.Item>
        <Form.Item
          label='Product Price'
          name='price'
          rules={[{ required: true }]}
        >
          <InputNumber min={1} />
        </Form.Item>
        <Form.Item
          label='Product Category'
          name='category'
          rules={[{ required: true }]}
        >
          <Select placeholder='Select a Category'>
            {categoryList.map(category => (
              <Option key={category._id} value={category._id}>
                {category.name}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item
          label='Product Stock'
          name='stock'
          rules={[{ required: true }]}
        >
          <InputNumber min={0} />
        </Form.Item>
        <Form.Item
          label='Shipping'
          name='shipping'
          valuePropName='checked'
          initialValue={false}
        >
          <Switch />
        </Form.Item>
        <Form.Item
          wrapperCol={{
            offset: indent,
          }}
        >
          <Button type='primary' htmlType='submit' loading={loading}>
            Create Product
          </Button>
        </Form.Item>
      </Form>
    </Layout>
  )
}
